import logging
import os
import re
import time


class LoggerUtil:
    _logger = None

    @classmethod
    def get_logger(cls):
        if cls._logger is None:
            cls._logger = logging.getLogger("flask_app_logger")
            cls._logger.setLevel(logging.INFO)

            # 创建控制台处理器
            console_handler = logging.StreamHandler()
            console_formatter = logging.Formatter(
                '%(asctime)s - %(levelname)s - %(message)s',
                datefmt='%Y-%m-%d %H:%M:%S'
            )
            console_handler.setFormatter(console_formatter)
            cls._logger.addHandler(console_handler)

            # 创建文件处理器
            log_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), "logs")
            os.makedirs(log_dir, exist_ok=True)
            
            # 创建文件格式化器
            file_formatter = logging.Formatter(
                '%(asctime)s - %(levelname)s - %(message)s',
                datefmt='%Y-%m-%d %H:%M:%S'
            )
            
            # 普通日志文件
            current_date = time.strftime('%Y-%m-%d', time.localtime())
            info_file_path = os.path.join(log_dir, f"{current_date}.log")
            info_handler = logging.FileHandler(info_file_path, encoding='utf-8')
            info_handler.setLevel(logging.INFO)
            info_handler.setFormatter(file_formatter)
            info_handler.addFilter(RemoveColorFilter())
            
            # 错误日志文件
            error_file_path = os.path.join(log_dir, f"{current_date}_error.log")
            error_handler = logging.FileHandler(error_file_path, encoding='utf-8')
            error_handler.setLevel(logging.ERROR)
            error_handler.setFormatter(file_formatter)
            error_handler.addFilter(RemoveColorFilter())
            
            cls._logger.addHandler(info_handler)
            cls._logger.addHandler(error_handler)

            # 确保错误不会被忽略
            cls._logger.propagate = False

            cls._logger.info(f"logger日志记录器初始化成功 实例ID:{id(cls._logger)}")
        return cls._logger

class RemoveColorFilter(logging.Filter):
    ansi_escape = re.compile(r'\x1B\[[0-?]*[0-9;]*[ -/]*[@-~]')
    def filter(self, record):
        record.msg = self.ansi_escape.sub('', record.msg)
        return True

